import {
  OnGatewayConnection,
  SubscribeMessage,
  WebSocketGateway,
  WebSocketServer,
} from '@nestjs/websockets';
import { ChatService } from './chat.service';
import { Server, Socket } from 'socket.io';

@WebSocketGateway({ cors: { origin: '*' } })
export class ChatGateway implements OnGatewayConnection {
  constructor(private readonly chatService: ChatService) {}

  @WebSocketServer()
  server: Server;

  // 当客户端调用 connection 事件时触发
  handleConnection(client: Socket) {
    const userId = client.handshake.query.userId;
    if (userId) {
      client.join(userId);
    } else {
      console.error('Missing userId in connection');
      client.disconnect(); // 或者处理不连接的逻辑
    }
  }

  // 当客户端调用 disconnect 事件时触发
  handleDisconnection(client: Socket) {
    console.log('Client disconnected:', client.id);
    const userId = client.handshake.query.userId;
    if (userId) {
      if (Array.isArray(userId)) {
        userId.forEach((id) => {
          client.leave(id);
        });
      } else {
        client.leave(userId);
      }
    }
  }

  @SubscribeMessage('call')
  handleCall(
    client: Socket,
    payload: { fromUserId: string; toUserId: string },
  ): void {
    console.log('call', payload.fromUserId, payload.toUserId);
    client.to(payload.toUserId).emit('message', {
      type: 'call',
      data: payload,
    });
  }

  @SubscribeMessage('acceptCall')
  handleAcceptCall(
    client: Socket,
    payload: { fromUserId: string; toUserId: string },
  ): void {
    console.log('acceptCall', payload.fromUserId, payload.toUserId);
    client.to(payload.toUserId).emit('message', {
      type: 'acceptCall',
      data: payload,
    });
  }

  @SubscribeMessage('hangUpCall')
  handleHangUpCall(
    client: Socket,
    payload: { fromUserId: string; toUserId: string },
  ): void {
    console.log('hangUpCall', payload.fromUserId, payload.toUserId);
    client.to(payload.toUserId).emit('message', {
      type: 'hangUpCall',
      data: payload,
    });
  }

  @SubscribeMessage('offer')
  handleOffer(
    client: Socket,
    payload: {
      fromUserId: string;
      toUserId: string;
      offer: RTCSessionDescriptionInit;
    },
  ): void {
    console.log('offer', payload.fromUserId, payload.toUserId);
    client.to(payload.toUserId).emit('message', {
      type: 'offer',
      data: payload,
    });
  }

  @SubscribeMessage('answer')
  handleAnswer(
    client: Socket,
    payload: {
      fromUserId: string;
      toUserId: string;
      answer: RTCSessionDescriptionInit;
    },
  ): void {
    console.log('answer', payload.fromUserId, payload.toUserId);
    client.to(payload.toUserId).emit('message', {
      type: 'answer',
      data: payload,
    });
  }

  @SubscribeMessage('candidate')
  handleCandidate(
    client: Socket,
    payload: {
      fromUserId: string;
      toUserId: string;
      candidate: RTCIceCandidateInit;
    },
  ): void {
    console.log('candidate', payload.fromUserId, payload.toUserId);
    client.to(payload.toUserId).emit('message', {
      type: 'candidate',
      data: payload,
    });
  }

  // 翻译相关
  @SubscribeMessage('audioBuffer')
  handleOriginBuffer(
    client: Socket,
    payload: { fromUserId: string; toUserId: string; blob: Blob },
  ): void {
    // 这里负责将 audiobuffer 转为文本，然后翻译成英文，最后转为翻译流转成buffer发出

    client.to(payload.fromUserId).emit('message', {
      type: 'translateBuffer',
      data: payload,
    });
  }
}
